<template>

  <x-form ref="formRef" v-model:model="form" :rules="rules" label-placement="top" label-width="120">
    <n-form-item path="v" :show-label="false" :ignore-path-change="true">
      <upload :accept="`image/*`" :key="imageKey" :rules="mediaRule" :defaultUpload="false" ref="uploadRef"
        @finish="finish" :params="waitUploadParams" :value="{ meta_type: '', media_url: '' }">
      </upload>
    </n-form-item>
    <n-form-item :label="formLabel.input" path="text">
      <n-input v-model:value="form.text" :maxlength="rules.textMaxLength"></n-input>
    </n-form-item>

  </x-form>

</template>
<script setup lang="ts">
import { reactive, computed } from 'vue';
import { ref } from 'vue';
import Upload from './upload.vue';
import { useStore } from '@/store';
// media Update Code ok
import MediaObj from '@/store/modules/adv/component/media/single';
import { XForm } from '@/components';
import { CloseCircleFilled } from '@vicons/antd'
import { NIcon, NSpin, NInput, NImage, NButton, NFormItem } from 'naive-ui';
const emit = defineEmits(['submit'])
const props = withDefaults(defineProps<{
  params?: any
  rules: any
  formLabel: {
    input: ''
  }
}>(), {
  rules: {
    textMaxLength: 12,
    media: {
      rect: [],
      suggest: [500, 500],
      // kb
      size: 100 * 1024,
      ratio: [],
      duration: [],
      file_format: [],
    }
  }
});

const media = reactive(new MediaObj({}))
const text = ref('1111');
const uploadRef = ref();
const imageKey = ref(Date.now());
const form = reactive({
  text: ''
})



const waitUploadParams = computed(() => {
  return {
    action: props.params.action,

    data: {
      ...props.params.data,
      fileName: form.text
    }
  }
})
const load = ref(false);
const mediaRule = computed(() => {
  return props.rules.media ? props.rules.media : {
    rect: [],
    suggest: [500, 500],
    // kb
    size: 100 * 1024,
    ratio: [],
    duration: [],
    file_format: [],
  }
})

const rules = reactive({
  text: {
    type: 'string',
    required: true,
    trigger: ['change'],
    message: '请输入内容' + props.formLabel.input
  },
})

function getInfo() {
  return {
    media,
    text
  }
}


function finish() {
  // console.log('any');
}

const formRef = ref();

async function submit() {
  return new Promise((resolve, reject) => {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        try {
          const info = await uploadRef.value.submit();
          text.value = '';
          imageKey.value = Date.now();
          resolve(info);
        } catch (error) {
          reject()
        }

      } else {
        reject()
      }
    })
  })


}

defineExpose({
  getInfo,
  submit
})

</script>
<style lang="scss" scoped>
@import url('./style.scss');

.input-container {
  margin-top: 30px;
}
</style>
